<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>账目管理</el-breadcrumb-item>
      <el-breadcrumb-item>账目记录</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <div class="header">
        <el-tag>收支总和: {{ calculateTotal }}</el-tag>
        <h2>收支总表</h2>

        <div>
          <el-button type="primary" @click="AddDialogVisible = true"
            >添加条目</el-button
          >
          <el-button type="primary" @click="handleExport()"
            >导出表格</el-button
          >
        </div>
      </div>

      <!-- 用户列表区域 -->
      <el-table :data="accountlist" border stripe ref="myTable">
        <el-table-column label="*" type="index"></el-table-column>
        <el-table-column label="金额" prop="amount"></el-table-column>
        <el-table-column label="日期" prop="date"></el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>
        <el-table-column label="类别" prop="categoryName"> </el-table-column>

        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showUpdateDialog(scope.row.transactionId)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeTransactionById(scope.row.transactionId)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="增加一条账目"
      :visible.sync="AddDialogVisible"
      width="30%"
    >
      <!-- 对话框主体区域 -->
      <el-form ref="AddFormRef" :model="AddForm" label-width="80px">
        <el-form-item label="金额">
          <el-input v-model="AddForm.amount"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="AddForm.description"></el-input>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="AddForm.date"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类别id">
          <el-input v-model="AddForm.categoryId"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="AddDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改的对话框 -->
    <el-dialog title="修改" :visible.sync="updateDialogVisible" width="30%">
      <!-- 对话框主体区域 -->
      <el-form :model="updateForm" label-width="80px">
        <el-form-item label="金额">
          <el-input v-model="updateForm.amount"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="updateForm.description"></el-input>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="updateForm.date"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类别id">
          <el-input v-model="updateForm.categoryId"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpdateForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { saveAs } from "file-saver";
import * as XLSX from "xlsx";
export default {
  data() {
    return {
      //帐单列表
      accountlist: [],
      //
      AddDialogVisible: false,
      //增加的表单 点击的时候作为参数传给后端
      AddForm: {
        date: "",
        description: "",
        amount: "",
        categoryId: "",
      },
      //修改的对话框
      updateDialogVisible: false,
      //修改的表单
      updateForm: {},
    };
  },
  created() {
    const id = window.sessionStorage.getItem("userId");
    this.getAccountList(id);
  },
  methods: {
    //获取表单
    async getAccountList(id) {
      const { data: res } = await this.$http.get(`transactionsList1/${id}`);
      this.accountlist = res;
    },

    async submitAddForm() {
      // 格式化日期
      this.AddForm.date = moment(this.AddForm.date).format("YYYY-MM-DD");
      this.AddForm.userId = window.sessionStorage.getItem("userId");

      const { data: res } = await this.$http.post(
        `transactionsAdd`,
        this.AddForm
      );
      if (res === 0) return this.$message.error("插入失败");

      this.AddDialogVisible = false;
      this.getAccountList(window.sessionStorage.getItem("userId"));
    },
    //根据id查询对应的账目记录
    async showUpdateDialog(id) {
      const { data: res } = await this.$http.get(`transactionsById/${id}`);
      this.updateForm = res;

      this.updateDialogVisible = true;
    },
    //提交修改
    async submitUpdateForm() {
      const { data: res } = await this.$http.put(
        `transactionsUpdate`,
        this.updateForm
      );
      if (!res) return this.$message.error("fail");
      this.updateDialogVisible = false;
      this.getAccountList(window.sessionStorage.getItem("userId"));
    },
    //删除t 通过模板传过来的id
    async removeTransactionById(id) {
      //弹出确定取消框，是否删除用户
      const confirmResult = await this.$confirm(
        "请问是否要永久删除该用户",
        "删除提示",
        {
          confirmButtonText: "确认删除",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //如果用户点击确认，则confirmResult 为'confirm'
      //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult != "confirm") {
        return this.$message.info("已经取消删除");
      }
      //发送请求根据id完成删除操作
      const { data: res } = await this.$http.delete("transactions/" + id);
      //判断如果删除失败，就做提示
      if (res === 0) return this.$message.error("删除用户失败");
      //修改成功的提示
      this.$message.success("删除用户成功");
      //重新请求最新的数据
      this.getAccountList(window.sessionStorage.getItem("userId"));
    },
    //导出功能
    handleExport() {  
    
    // 使用ref获取  
    const wb = XLSX.utils.table_to_book(this.$refs.myTable.$el.querySelector('.el-table__body-wrapper tbody'), { sheet: 'Sheet1' });  
  
    // 生成Excel文件的二进制字符串表示  
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });  
  
    // 创建一个Blob对象，表示一个不可变、原始数据的类文件对象  
    const blob = new Blob([wbout], { type: 'application/octet-stream' });  
  
    // 使用FileSaver保存文件  
    saveAs(blob, 'exported-table.xlsx');  
  }  
  },
  computed: {
    calculateTotal() {
      // 计算总金额
      const money = this.accountlist.reduce(
        (total, item) => total + item.amount,
        0
      );

      //
      const formattedMoney = parseFloat(money.toFixed(2)); // 使用parseFloat确保结果为数值类型

      // 存储到sessionStorage
      window.sessionStorage.setItem("money", formattedMoney.toString()); // 转换为字符串存储

      return money;
    },
  },
};
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>